package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"logi-perm-sys/cache"
	"logi-perm-sys/modles"
	"strconv"
	"time"
)

func PeopleOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	/*

		SELECT
		orders.id As OrderID,
		orders.order_name AS OrderName,
		orders.order_status AS OrderStatus,
		peoples.people_name AS PeopleName,
		peoples.people_code AS PeopleCode,
		peoples.email AS Email,
		peoples.peo_ple_tel AS PeoPleTel,
		peoples.people_age AS PeopleAge
		FROM
		orders
		LEFT JOIN peoples on peoples.id=orders.pid

	*/

	var data []modles.OrderPeopleList

	redis_key := "people_order_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		modles.DB.
			Table("orders").
			Select("orders.id As OrderID",
				"orders.order_name AS OrderName",
				"orders.order_status AS OrderStatus",
				"peoples.people_name AS PeopleName",
				"peoples.people_code AS PeopleCode",
				"peoples.email AS Email",
				"peoples.peo_ple_tel AS PeoPleTel",
				"peoples.people_age AS PeopleAge",
			).
			Joins("LEFT JOIN peoples on peoples.id=orders.pid").
			Debug().
			Offset(offset).
			Limit(size).
			Find(&data)

		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}

	var total int64
	modles.DB.Model(&modles.Order{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  data,
		"count": total,
	})
	return

}

func PeopleOrderDetail(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	/*
		SELECT
		orders.id As OrderID,
		orders.order_name AS OrderName,
		orders.order_status AS OrderStatus,
		peoples.people_name AS PeopleName,
		peoples.people_code AS PeopleCode,
		peoples.email AS Email,
		peoples.peo_ple_tel AS PeoPleTel,
		peoples.people_age AS PeopleAge
		FROM
		orders
		LEFT JOIN peoples on peoples.id=orders.pid
	*/
	var data modles.OrderPeopleList
	redis_key := "people_order_detail_id_" + strconv.Itoa(id)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		modles.DB.
			Table("orders").
			Select("orders.id As OrderID",
				"orders.order_name AS OrderName",
				"orders.order_status AS OrderStatus",
				"peoples.people_name AS PeopleName",
				"peoples.people_code AS PeopleCode",
				"peoples.email AS Email",
				"peoples.peo_ple_tel AS PeoPleTel",
				"peoples.people_age AS PeopleAge",
			).
			Joins("LEFT JOIN peoples on peoples.id=orders.pid").
			Debug().
			Where("orders.id=?", id).
			Find(&data)

		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": data,
	})
	return
}
